import api from '../../axios/axios';
import type {
  ProblemCreateRequest,
  ProblemListRequest,
  Tag as TagType,
  ProblemCase
} from '../../dto/problemManagement';
import type {
  ProblemListResponse
} from '../../vo/problemManagement';

import type {
  ProblemCreateResponse
} from '../../vo/problemManagement';

// 构造题目创建请求数据
export const buildProblemCreateRequest = (
  values: any,
  description: string,
  testCases: ProblemCase[],
  availableTags: TagType[]
): ProblemCreateRequest => {


  const content = description;

  // 难度映射
  const difficultyMap = {
    'easy': 1,
    'medium': 2,
    'hard': 3
  };

  return {
    problem: {
      problemId: values.problemId || undefined,
      title: values.title,
      author: values.author || 'admin',
      status: values.isPublic ? 1 : 0,
      type: values.type || 0,
      timeLimit: values.timeLimit,
      memoryLimit: values.memoryLimit,
      stackLimit: values.stackLimit || 128,
      description: content,
      inputDescription: '',
      outputDescription: '',
      difficulty: difficultyMap[values.difficulty as keyof typeof difficultyMap] || 0,
      hint: '',
      auth: values.auth || 1,
      judgeMode: 'default',
      judgeCaseMode: 'default',
      content: content
    },
    samples: testCases.map(testCase => ({
      input: testCase.input,
      output: testCase.output,
      score: 100
    })),
    isUploadTestCase: false,
    judgeMode: 'default',
    languages: values.supportedLanguages?.map((lang: string) => ({
      name: lang,
      codeTemplate: ''
    })) || [],
    problemTags: values.tags?.map((tagName: string) => {
      const tagInfo = availableTags.find(t => t.name === tagName);
      return {
        id: tagInfo?.id,
        name: tagName,
        color: tagInfo?.color || '#1890ff',
        oj: 'swust',
        gid: 0
      };
    }) || []
  };
};

// 题目管理相关API
export const problemManagementApi = {
  // 创建题目（使用新的数据结构）
  createProblem: (data: ProblemCreateRequest): Promise<ProblemCreateResponse> => {
    return api.post('/admin/problem/create', data);
  },

  // 获取题目列表（分页）
  getProblemList: (params: ProblemListRequest): Promise<ProblemListResponse> => {
    return api.post('/user/problem/list', params);
  },

  // 获取题目详情（用于编辑）
  getProblemForEdit: (id: string): Promise<{
    code: number;
    message: string;
    data: ProblemCreateRequest & { id: string };
  }> => {
    return api.get(`/admin/problems/${id}`);
  }
};

export default problemManagementApi;